package org.jash.demo2205.shop

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import org.jash.demo2205.dao.GoodsDao
import org.jash.demo2205.entity.BannerEntity
import org.jash.demo2205.entity.Category
import org.jash.demo2205.entity.Goods
import org.jash.demo2205.mvvm.BaseViewModel
import javax.inject.Inject

@HiltViewModel
class HomeViewModel @Inject constructor(val goodsDao: GoodsDao):BaseViewModel() {
    val goodsLiveData by lazy { MutableLiveData<List<Goods>>()}
    val bannersLiveData by lazy { MutableLiveData<List<BannerEntity>>()}
    val searchLiveData by lazy { MutableLiveData<List<Goods>>() }
    val categoriesLiveData by lazy { MutableLiveData<List<Category>>() }

    fun getCategories() {
        viewModelScope.launch {
            try {
                val res = service.getAllCategory()
                if (res.code == 200) {
                    categoriesLiveData.postValue(res.data)
                } else {
                    throw RuntimeException(res.message)
                }
            } catch (e:Exception) {
                failureLiveData.postValue(e)
            }
        }
    }

    fun getGoods(cid:Int, page:Int, size:Int) {
        viewModelScope.launch {
            try {
                val res = service.getGoods(cid, page, size)
                if (res.code == 200) {
                    goodsDao.save(*res.data.toTypedArray())
                    goodsLiveData.postValue(res.data)
                } else {
                    throw RuntimeException(res.message)
                }
            } catch (e:Exception) {
                failureLiveData.postValue(e)
            }
        }

    }
    fun getBanners() {
        viewModelScope.launch {
            try {
                val res = service.getBanners()
                if (res.code == 200) {
                    bannersLiveData.postValue(res.data)
                } else {
                    throw RuntimeException(res.message)
                }
            } catch (e:Exception) {
                failureLiveData.postValue(e)
            }
        }

    }
    fun search(keyword:String) {
        viewModelScope.launch {
            try {
                searchLiveData.postValue(goodsDao.search("%$keyword%"))
//                val res = service.getGoods(0, 1, 100)
//                if (res.code == 200) {
//                    searchLiveData.postValue(res.data.filter { keyword in it.goods_desc })
//                } else {
//                    throw RuntimeException(res.message)
//                }
            } catch (e:Exception) {
                failureLiveData.postValue(e)
            }
        }

    }
}